package com.itheima.interceptors;

import cn.hutool.json.JSONUtil;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.utils.JedisUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: wolf
 * @Description:
 * @Date: Created in 20:51 2020-01-09
 * @Modified By:
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisUtil jedisUtil;

//    private static final Logger LOGGER=Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token==null || token.length()==0 || token.equals("null")){
            canNotLogin(response);
//            LOGGER.warn("您不具备权限，请先登录");
            return false;
        }

        String s = jedisUtil.get(token);
        if (s == null) {
            canNotLogin(response);
//            LOGGER.warn("请先登录");
            return false;
        }
        Member member = JSONUtil.toBean(s, Member.class);

        if(member == null ){
            canNotLogin(response);
//            LOGGER.warn("请先登录");
            return false;
        }
            //再去数据库检查其身份对不对，是否冻结。。。
//            LOGGER.info(member.getName()+"处于登录状态，可以执行操作");
            return true;

    }

    private void canNotLogin(HttpServletResponse response) throws IOException {
        Result result = new Result(false, "没有登陆", "401");
        response.setContentType("application/json;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONUtil.toJsonStr(result));
        writer.close();
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}